package clientCommunicationHandler;

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.util.Vector;

import communication.*;

public class UserInterfaceMsgHandler {
	
	private final String delimiter = (char)1+"";
	
	public String parserUserChooice(int lineIndex,String [] menuToChooseFrom){
		String line = menuToChooseFrom[lineIndex];
		String[] lineArray = line.split(" ");
		String command = lineArray[1];
		int restOfLinelength = lineArray.length - 2;
		String[] restOfline = new String[restOfLinelength];
		System.arraycopy(lineArray, 2, restOfline, 0, restOfLinelength);
		String sendToServer = getMessageForServer(command,restOfline); 

		return sendToServer;

	}

	private String getMessageForServer(String command1, String[] restOfline) {
		String tempMessageForServer ="";
		String command = getServerCommand(command1);
		if(command.equalsIgnoreCase("Logout\n")){
			tempMessageForServer = "logout"+delimiter+UserInfo.userName+delimiter;
			UserInfo.userPosition.removeAllElements();
			UserInfo.wantToAddModeratorToSubForum = "";
			UserInfo.wantToRemoveModeratorToSubForum = "";
		}
		if(command.equalsIgnoreCase("Login\n")){
			tempMessageForServer = handleLoginForm();
		}
		if(command.equalsIgnoreCase("register\n"))
			tempMessageForServer = handleRegisterForm();
		if(command.equalsIgnoreCase("view_Forums\n")){
			tempMessageForServer = handleViewForums();
		}
		if(command.equalsIgnoreCase("viewThreads")){
			String threadId = restOfline[0].split(":")[0];
			tempMessageForServer = handleViewThreads(threadId);
		} 
		if(command.equalsIgnoreCase("add\n")||tempMessageForServer.equalsIgnoreCase("add")){
			if(UserInfo.userName != "guest"){
				tempMessageForServer = handleAddNewMsg();
			}
			else{
				System.out.println("you are not login.\n in order to post you must to login\n redirecting to welcomPage... ");
				TelnetClient.menu = TelnetClient.welcom_page;
			}
		}
		if(command.equalsIgnoreCase("addPost")){
			tempMessageForServer = handleNewPostMsg(restOfline[0],"false");
		}
		if(command.equalsIgnoreCase("addFirstPost")){
			tempMessageForServer = handleNewPostMsg(restOfline[0],"true");
		}
		if(command.equalsIgnoreCase("Post")){
			tempMessageForServer = UserInfo.backHandler.refresh();

		}
		if(command.equalsIgnoreCase("back\n")||command.equalsIgnoreCase("back")){
			tempMessageForServer = handleBackMsg();
		}
		if(command.equalsIgnoreCase("viewSubForum"))
			tempMessageForServer = handleViewSubForum(restOfline[0].split(":")[0]);
		if(command.equalsIgnoreCase("add-new-SubForum")||tempMessageForServer.equalsIgnoreCase("add-new-SubForum\n")){
			tempMessageForServer = addNewSubForum();
		}
		if(command.equalsIgnoreCase("add-moderator")){
			tempMessageForServer = askForCandidatModerators(restOfline[2]);
		}
		if(command.equalsIgnoreCase("deleteSubForum")){
			tempMessageForServer = deleteSubForum(restOfline[0]);
		}
		if(command.equalsIgnoreCase("removePost")){
			tempMessageForServer = deleteMsg(restOfline[0],"false");
		}
		if(command.equalsIgnoreCase("removeFirstPost")){
			tempMessageForServer = deleteMsg(restOfline[0],"true");
		}
		if(command.equalsIgnoreCase("remove-moderator")){
			tempMessageForServer = getModerator(restOfline[2]);
		}
		if(command.equalsIgnoreCase("chooseModeratorToRemove")){
			tempMessageForServer = removeModerator(restOfline[0]);
		}
		if(command.equalsIgnoreCase("editPost")){
			tempMessageForServer = editPost(restOfline[0],"false");
		}
		if(command.equalsIgnoreCase("editFirstPost")){
			tempMessageForServer = editPost(restOfline[0],"true");
		}
		if(command.equalsIgnoreCase("editMsg")){
			tempMessageForServer = editPost(restOfline[0]);
		}
		if(command.equalsIgnoreCase("exit")){
			tempMessageForServer = exit();
		}
		if(command.equalsIgnoreCase("chooseModeratorToAdd")){
			tempMessageForServer = buildAddModeratorServerStyle(command1);
		}

		return tempMessageForServer;
	}
	
	
	private String buildAddModeratorServerStyle(String command1) {
		int newLineIndex = command1.lastIndexOf("\n");
		
		String moderatorName =(newLineIndex > 0? command1.substring(0,newLineIndex):"");
		String subForumId = UserInfo.wantToAddModeratorToSubForum;
		int newLineIndexOfSubForumId = subForumId.indexOf("\n");
		subForumId = (subForumId.indexOf("\n") < 0 ? UserInfo.wantToAddModeratorToSubForum : UserInfo.wantToAddModeratorToSubForum.substring(0, newLineIndexOfSubForumId));
		String serverCommand = "addModerator"+delimiter+UserInfo.userName+delimiter+moderatorName+delimiter+subForumId+delimiter;
		UserInfo.wantToAddModeratorToSubForum = "";
		return serverCommand;
	}

	private String getServerCommand(String command1) {
		if(!UserInfo.wantToAddModeratorToSubForum.equalsIgnoreCase("")
				&& !command1.equalsIgnoreCase("back")
				&& !command1.equalsIgnoreCase("logout")&& !command1.equalsIgnoreCase("logout\n"))
			return "chooseModeratorToAdd";
		if(!UserInfo.wantToRemoveModeratorToSubForum.equalsIgnoreCase("")
				&& !command1.equalsIgnoreCase("back")
				&& !command1.equalsIgnoreCase("logout")&& !command1.equalsIgnoreCase("logout\n"))
			return "chooseModeratorToRemove";
		return command1;
	}

	private String exit() {
		// TODO Auto-generated method stub
		return "bye"+delimiter;
	}

	private String editPost(String post) {
		String editedMsgId = post.split(":")[0];
		ReadNewMsg tMsg = new ReadNewMsg();
		String newMsg = tMsg.readMsgFromUser();
		String sendToServer = buildEditMsg(newMsg,editedMsgId);
		return sendToServer;
	}
	private String buildEditMsg(String newMsg, String editedMsgId) {
		String msgForServer = "editMsg"+delimiter+UserInfo.userName+delimiter+this.getUserPositionInServerFormat()+editedMsgId+delimiter+newMsg+delimiter;
		return msgForServer;
	}
	private String editPost(String post,String firstPost) {
		String editedMsgId = post.split(":")[0];
		ReadNewMsg tMsg = new ReadNewMsg();
		String newMsg = tMsg.readMsgFromUser();
		String sendToServer = buildEditMsg(newMsg,editedMsgId,firstPost);
		return sendToServer;
	}
	private String buildEditMsg(String newMsg, String editedMsgId,String firstPost) {
		String msgForServer = "editMsg"+delimiter+UserInfo.userName+delimiter+this.getUserPositionInServerFormat()+editedMsgId+delimiter+newMsg+delimiter+firstPost+delimiter;
		return msgForServer;
	}
	private String removeModerator(String moderatorName) {
		int newLineIndex = moderatorName.indexOf("\n");
		String moderatorName1 = (newLineIndex > 0 ? moderatorName.substring(0, newLineIndex) : moderatorName);
		String sendToServer = "removeModerator"+delimiter+UserInfo.userName+delimiter+UserInfo.wantToRemoveModeratorToSubForum+delimiter+moderatorName1 +delimiter;
		UserInfo.wantToRemoveModeratorToSubForum ="";
		return sendToServer;
	}

	private String getModerator(String subForumId) {
		int newLineIndex = subForumId.indexOf("\n");
		String subForumId1 = (newLineIndex > 0 ? subForumId.substring(0, newLineIndex) : subForumId);
		String userName = UserInfo.userName;
		UserInfo.wantToRemoveModeratorToSubForum = subForumId1;
		return "getModerators"+delimiter+userName+delimiter+subForumId1+delimiter;
		
	}
	private String deleteMsg(String post,String firstPost) {
		String msgId = post.split(":")[0];
		return "deleteMsg"+delimiter+UserInfo.userName+delimiter+getUserPositionInServerFormat()+msgId+delimiter+firstPost+delimiter;
	}
	
	private String askForCandidatModerators(String subForumID) {
		UserInfo.wantToAddModeratorToSubForum = subForumID;
		int newLineIndex = subForumID.indexOf("\n");
		String forumId = subForumID.substring(0, newLineIndex);
		return "moderatorsCandidate"+delimiter+UserInfo.userName+delimiter+forumId+delimiter;
	}
	private String deleteSubForum(String subForumIdToDelete) {
		int newLineDelimiter = subForumIdToDelete.indexOf("\n");
		String subForumId = subForumIdToDelete.substring(0, newLineDelimiter);
		return "DeleteSubForum"+delimiter+UserInfo.userName+delimiter+subForumId+delimiter;
	}
	
	private String addNewSubForum() {
		String subForumName = "";
		while(subForumName.equals("")){
			try {
				System.out.println("please enter sub forum name");
				subForumName = TelnetClient.in.readLine();
			} catch (IOException e) {
				e.printStackTrace();
				subForumName =  "";
			}
		}
		return "addSubForum"+delimiter+UserInfo.userName+delimiter+subForumName+delimiter;
	}
	private String handleViewSubForum(String userTempPosition) {
		UserInfo.tempUserNextPosition = userTempPosition;
		String temp = "viewSubForum"+delimiter+UserInfo.userName+delimiter+userTempPosition+delimiter;
		return temp;
	}
	
	private String handleBackMsg() {
		UserInfo.wantToAddModeratorToSubForum = "";
		UserInfo.wantToRemoveModeratorToSubForum = "";
		String temp = UserInfo.backHandler.back();
		return temp;
	}
	private String getUserPositionInServerFormat() {
		String pos = "";
		for(int i = 0;i<UserInfo.userPosition.size();i++){
			pos += UserInfo.userPosition.elementAt(i)+delimiter;
		}
		return pos;
	}
	private String handleAddNewMsg() {
		ReadNewMsg tMsg = new ReadNewMsg();
		String msg = tMsg.readMsgFromUser();
//		System.out.println("handleAddNewMsg: userPosition is: "+UserInfo.userPosition);
		String temp = "";
		String userPositionServerFormat = this.getUserPositionInServerFormat();
		if(UserInfo.userPosition.size() <= 1) {
			temp ="addThread"+delimiter+UserInfo.userName+delimiter+userPositionServerFormat+msg+delimiter;
		}
		else{
			temp = "addPost"+delimiter+UserInfo.userName+delimiter+msg+delimiter+userPositionServerFormat;
		}
		return temp;
	}
	/**
	 * read new post message
	 * and automatically asking for  refresh view
	 * @param postId the post id which the user want to response to 
	 * @return server message format for adding new post + refresh new view;
	 */
	private String handleNewPostMsg(String postId,String firstPost) {
		ReadNewMsg tMsg = new ReadNewMsg();
		int indexOfNewLine = postId.indexOf("\n");
		String post = postId.substring(0,indexOfNewLine);
		String msg = tMsg.readMsgFromUser();
		String temp = "addPost"+delimiter+UserInfo.userName+delimiter+this.getUserPositionInServerFormat()+post+delimiter+msg+delimiter+firstPost+delimiter;
		return temp;
	}
	
	
	/**
	 * 
	 * @param threadID
	 * @return server viewThread message format 
	 */
	private String BuildViewThreadMsg(String threadID) {
//		delimiter+this.getUserPositionInServerFormat()+
		return "viewThread"+delimiter+UserInfo.userName+delimiter+getUserPositionInServerFormat()+threadID+delimiter;
	}
	
	private String handleViewThreads(String threadId) {
		String temp = BuildViewThreadMsg(threadId);//"viewThread\n"+TelnetClient.SubForumId+"\n"+ tMenuInArray[2].split(":")[0]+"\n\0\n";
		UserInfo.tempUserNextPosition = threadId;
		return temp;
	}

	private String handleViewForums() {
		String temp = "viewForum"+delimiter+UserInfo.userName+delimiter;
		UserInfo.userPosition = new Vector<String>();
		return temp;
	}


	/**
	 * 
	 * @param in buffer reader
	 * @return user name
	 */
	private String readUserName(BufferedReader in){
		System.out.println("enter your user name:");
		String tUserName = null;
		while(tUserName == null){
			try {
				tUserName = in.readLine();
//				System.out.println("UserIntegerface readFromFile "+ tUserName);
				if(tUserName.equals("")){
					tUserName = null;
					System.out.println("invalid user name please re-enter your user name");		
				}
			} catch (IOException e) {
				e.printStackTrace();
				tUserName = null;
			}
		}
		//save the temporary user name,for future management.
		UserInfo.tempUserName = tUserName;
		return tUserName;

	}

	/**
	 * 
	 * @param in buffer reader
	 * @return user password
	 */
	private String readUserPass(BufferedReader in){
		Console c = System.console();
		UserProxyPasswordReader pass = new UserProxyPasswordReader();
		pass.setBuffer(in);
		pass.setConsole(c);
		return pass.readPassword();
	}


	private String handleLoginForm() {
		//		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		//		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String tUserName = readUserName(TelnetClient.in);
		String tPass = readUserPass(TelnetClient.in);
		String result = createLoginMsg(tUserName, tPass);
		return result;
	}
	
	public String createLoginMsg(String tUserName, String tPass) {
		String result = "login"+delimiter+tUserName+delimiter+tPass+delimiter;
//		if(UserInfo.userPosition.size() < 1)
//			ClientServerMsgHandler.buildMenu = true;
//		else{
//			ClientServerMsgHandler.buildMenu = false;
//			result += refreshView();
//		}
		return result;
	}
	
	/**
	 * read from the user username and user password
	 * @post username != ""
	 * @post password !=""
	 * @return server login message format
	 */

	private  String handleRegisterForm() {
		String tUserName = readUserName(TelnetClient.in);
		String tPass = readUserPass(TelnetClient.in);
		return "register"+delimiter+tUserName+delimiter+tPass+delimiter;
	}



}


